//  配置
var _config = {
  //  base: 'http://t.imaisu.com',
  base: '',
  creatShortLink: '/api/job',
  /*
    {
      "phones": [123,244,333],
      "file_name": "test",
      "base_ur": "http://t.tt",
      "long_long_url": "http://mall-o.com",
      "product": "CK22",
      "delivery_source": "FEI_MSG",
      "template_id": 1,
      "delivery_time": "2018-05-01",
      "source": 1 # 1是单号 2是批量
  }
  */
  getProduct: '/api/product', //  查询货品
  getBaseUrl: '/api/base_url', //  查询根域名
  getDeliverySource: '/api/delivery_source', //  查询投放来源
  getTemplate: '/api/template',
  getLongUrl: '/api/long_url',
  getAmount: '/api/base_url/amount'
}

var _status = {
  0: '等待中',
  1: '生成中',
  2: '生成失败',
  3: '生成完毕',
}


//  业务逻辑
var _main = {
  data: {
    phoneArr: [],
    fileName: undefined
  },
  setSubmitBtn: function (_arr) {
      var _btn = document.querySelector('#createBtn');
      if (_arr && _arr.length && _arr[0].length) {
        _btn.disabled = false;
      } else {
        _btn.disabled = true;
      }
  },
  watchPhone: function () {
    var t = this;
    var _handle = function() {
      let _phone = this.value;
          _phone = _phone.split('\n');
          t.setSubmitBtn(_phone)
    }
    //  document.querySelector('#phone').addEventListener('change', _handle, false);
    document.querySelector('#phone').addEventListener('input', _handle, false);
  },
  //  点创建按钮
  submitCreateForm: function() {
    let _phone = document.querySelector('#phone').value;
        _phone = _phone.split('\n');
        _phone = _phone && !!_phone[0] ? this.data.phoneArr.concat(_phone) : this.data.phoneArr;
        //  去除空格
        /* _phone.forEach((e,i) => {
          if(!/\d+/.test(e)){
            _phone.splice(i, 1)
          }
        }); */
        console.log(_phone)
        if (!_phone || !_phone.length) {
          alert('请输入或批量上传手机号码')
          return
        }
    let _params = {
      "phones": _phone,
      "file_name": this.fileName || (new Date()).getTime() + '',
      "base_ur": this.getSelected(document.querySelector('#base_url')).text,
      "long_long_url": this.getSelected(document.querySelector('#long_url')).text,
      "product": this.getSelected(document.querySelector('#product')).text,
      "delivery_source": this.getSelected(document.querySelector('#delivery_source')).text,
      "template_id": +(document.querySelector('#template_id').value),
      "delivery_time": document.querySelector('#delivery_time').value,
      "source": this.fileName ? 2 : 1,
      "is_send": document.querySelector('#is_send').checked ? 1: 0,
      /* phones: _phone ? this.data.phoneArr.concat(_phone) : this.data.phoneArr,
      delivery_time: document.querySelector('#delivery_time').value,
      template_id: document.querySelector('#template_id').value,
      base_url_id: document.querySelector('#base_url').value,
      long_url_id: document.querySelector('#long_url').value,
      product_id: document.querySelector('#product').value,
      delivery_source_id: document.querySelector('#delivery_source').value */
    }
    alert('已提交任务');
    this.resetForm("onlyTxt");
    _utils.post(_config.creatShortLink, _params, (res) => {
      console.log(res)
      var _msg = this.servlize(res);
      document.querySelector('#create_result').value = _msg
      if (res.code == "200") {
        this.getJobsList();
      }
    })
  },
  getSelected: function (obj) {
    var _r = obj.options[obj.selectedIndex]
    return {
      text: _r.text,
      value: _r.value
    }
  },
  bindEvents: function () {
    document.querySelector('#createBtn').addEventListener('click', this.submitCreateForm.bind(this));
    // bind events
  	var excelfileObj = document.getElementById("excelfile");
  	excelfileObj.addEventListener('change', this.handleFile.bind(this), false);
     document.getElementById("refresh_table").addEventListener('click', this.getJobsList.bind(this), false);
     document.getElementById("resetBtn").addEventListener('click', this.resetForm.bind(this), false);
     this.watchPhone();
  },
  setSelectOptions: function (arr, key) {
    var _res = '';
    //arr = _utils.sortSelect(arr);
    arr.forEach((e, i) => {
      _res += '<option value="' + e['id'] + '" n="' + e[key] + '" >' + e[key] + '</option>'
    })
    return _res
  },
  //  序列化
  servlize: function (data) {
    var res = '';
    //for (var i = 0; i< data.length; i++) {
      for (var j in data/*[i]*/ ) {
       res += j + ':  ' + data/*[i]*/[j] + '\n';
      }
    //}
    return res
  },
  //  获取初始化数据\
  getInitData: function () {
    _utils.get(_config.getProduct, {
    }, (res) => {
      console.log(res)
      document.querySelector('#product').innerHTML = this.setSelectOptions(res, 'product_name');
    })
    _utils.get(_config.getBaseUrl, {
    }, (res) => {
      console.log(res)
      document.querySelector('#base_url').innerHTML = this.setSelectOptions(res, 'short_url');
    })
    _utils.get(_config.getDeliverySource, {
    }, (res) => {
      console.log(res)
      document.querySelector('#delivery_source').innerHTML = this.setSelectOptions(res, 'delivery_source');
    })
    _utils.get(_config.getTemplate, {
    }, (res) => {
      console.log(res)
      document.querySelector('#template_id').innerHTML = this.setSelectOptions(res, 'name');
    })
    _utils.get(_config.getLongUrl, {
    }, (res) => {
      console.log(res)
      document.querySelector('#long_url').innerHTML = this.setSelectOptions(res, 'long_url');
    })

    this.getAmount();

    this.getJobsList();
  },
  getJobsList: function (e) {
    _utils.get(_config.creatShortLink, {
    }, (res) => {
      console.log(res)
      document.querySelector('#result_table').innerHTML = this.setTableDate(res);
      this.getAmount();
    })
  },
  handleFile: function (e) {
	  var files = e.target.files, f = files[0];
    this.fileName = f.name;
	  var reader = new FileReader();
	  reader.onload = e => {
	    var data = e.target.result;
	    /* DO SOMETHING WITH workbook HERE */
	    this.fetchData(data)
	  };
	  reader.readAsText(f);
	},
  fetchData: function(data) {
			this.data.phoneArr = data ? data.split('\n'): [];
      this.setSubmitBtn(this.data.phoneArr)
	},
  setTableDate: function (data) {
    /*
        count:3
        created_at:"2018-05-08 00:23:03"
        delivery_source:"FEI_MSG"
        name:"单号-2018050723:40:50"
        product:"CK22"
        status:3
        text:"测试测试{{url}}"
        ID/生成名称/生成号码/商品类型/渠道来源/渠道描述/文案配置/创建时间/生成状态/操 作
      */

    var _r = "<tr>\
      <th>ID</th>\
      <th>生成名称</th>\
      <th width='60'>生成号码</th>\
      <th width='60'>商品类型</th>\
      <th>渠道来源</th>\
      <th width='60' >渠道描述</th>\
      <th>文案配置</th>\
      <th>创建时间</th>\
      <th width='60' >同步发送</th>\
      <th width='60' >生成状态</th>\
      <th>操作</th>\
    </tr>";
    data.forEach((e,i) => {
      var _send = '-';
      if (e['is_send'] == 1) {
        if (e['send_status'] == 1) {
          _send = '已发送'; 
        } else if (e['send_status'] == 0) {
          _send = '未发送';
        }
      }
      _r += '<tr>';
      /*for (var j in e ) {
        _r += '<td>' + e[j] + '</td>'
      }*/
      _r += '<td>' + e['id'] + '</td><td>' + e['name'].replace(/\.csv$/, '') + '</td><td>' + e['count'] + '</td><td>' + e['product'] + '</td>'
        + '<td>' + e['delivery_source'] + '</td><td>'+ e['delivery_time'] + '</td>'
        + '<td title="' + e['text'] + '"><textarea class="copyInp" id="' + e['id'] + '" readOnly >' + e['text'] + '</textarea>&emsp;<a href="javascript:void(0)" class="fr mgt5" onclick="copyById(' + e['id'] + ')">[复制]</a></td>'
        + '<td>' + e['created_at'] + '</td><td>' + _send + '</td><td><a href="/admin/' + e['id'] + '.txt" target="_blank">' + _status[e['status']] + '</a></td>';
      _r += '<td class="edit"><a href="' + _config.base + "/admin/" + e['name'].replace(/^(批量|单号)\-/, '') + '" download >下载</a>'
         + '<a href="javascript:void(0)" onclick="_main.delJob(' + e['id'] + ')" >删除</a></td>'
      _r += '</tr>';
    })
    return _r
  },
  //  删除
  delJob: function(id) {
    if (!confirm("确认删除:" + id + "?")) {
      return
    }
    _utils.del(_config.creatShortLink, {
      job_id: id
    }, (res) => {
      console.log(res)
      var _msg = this.servlize(res);
      document.querySelector('#create_result').value = _msg
      if (res.code == "200") {
        alert('删除成功')
        this.getJobsList();
      }
    })
  },
  init: function () {
    this.getInitData();
    this.bindEvents();
  },
  //  重置表单
  resetForm: function (onlyTxt) {
    var _arr = [document.querySelector('#phone'),
                document.querySelector('#base_url'),
                document.querySelector('#long_url'),
                document.querySelector('#product'),
                document.querySelector('#delivery_source'),
                document.querySelector('#template_id'),
                document.querySelector('#delivery_time')]
      if (onlyTxt && onlyTxt === "onlyTxt") {
        _arr.splice(1,5);
      }
      document.querySelector("#excelfile").value = '';
      this.data.phoneArr = [];
      for (var i = 0; i< _arr.length; i++){
        var _c = _arr[i];
        if (_c.nodeName === "INPUT" || _c.nodeName === "TEXTAREA") {
          _c.value = '';
        } else if (_c.nodeName === "SELECT") {
          _c.options[0].selected = true;
        }
      }
  },
  getAmount: function() {
    _utils.get(_config.getAmount, {
    }, (res) => {
      console.log(res)
      document.querySelector('#last_amount').value = _utils.formatTNum(res.amount);
    })
  },
  copyById(id) {
    var copyText = document.getElementById('' + id);
    copyText.select();
    document.execCommand("copy");
    alert("短信文案已复制");
  }
}
//  run
_main.init();

window.copyById = _main.copyById;
